<?php

namespace App\Models;


use App\Http\Common\Lib\Common;
use Illuminate\Database\Eloquent\Model;

class LoginRecord extends BaseModel
{
    //
    //
    public $timestamps =false;

    protected $validatorName = 'LoginRecord';

    /**
     * 管理员
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function adminUser(){
        return $this->belongsTo('App\Models\AdminUser','user_id','id');
    }
    public function user(){
        return $this->belongsTo('App\Models\User','user_id','id');
    }
    /**
     * 保存登陆记录
     * @param $id
     * @param int $type 1:普通用户,2:后台用户
     */
    static function saveRecord($id,$type=1){
        $ip = request()->getClientIp();
        $record = new LoginRecord();
        $ipInfo = Common::ipToAddress($ip);
        $address = '未知';
        if($ipInfo['status'] == config('statusInfo.status.success') && $ipInfo['data']){
            $ipData = $ipInfo['data'];
            $address = $ipData['country'].'.'.$ipData['region'].'.'.$ipData['city'];
        }
        $record->user_id = $id;
        $record->type = $type;
        $record->ip = $ip;
        $record->address = $address;
        $record->login_time = time();
        $record->save();
    }
}
